<?php
class Users extends CActiveRecord {
	/** User Status */
	const STATUS_ENABLE = 1;
	const STATUS_DISABLE = 2;
	/** User Genter */
	const GENDER_MALE = 1;
	const GENDER_FEMALE = 2;
	/** User Role */
	const ROLE_ADMIN = 2;
	const ROLE_USER = 1;
	
	const REGEXP_PASSWORD = '/^[0-9a-zA-Z]{6,20}$/';
	
//	public $password;
	public $confirmPassword;

	public $verifyCode;
	
	public static function model($className = __CLASS__) {
		return parent::model($className);
	}

	public function tableName() {
		return strtolower('Users');
	}
	
	public function rules() {
		return array(
			array('userEmail', 'required'),
			array('userPassword', 'compare', 'on' => array('resetPassword'), 'compareAttribute' => 'confirmPassword', 'message' => '两次输入密码不一致，请重新输入。'),
			array('userEmail', 'email'),
			array('userEmail', 'unique'),
			array('verifyCode', 'captcha', 'on' => array('signUp'))
		);
	}
	
	public function relations() {
		return array(
			'psy' => array(self::HAS_ONE, 'Psychologists', 'userId')
		);
	}
	
	public static function isLogin($redirect = false) {
		$result = isset(Yii::app()->user->id) ? Yii::app()->user->id : false;
		if($redirect === true && ! $result) {
			Yii::app()->loginRequired();
		}
		return $result;
	}
	
	public function stautsOptions() {
		return array(
			self::STATUS_ENABLE => '正常',
			self::STATUS_DISABLE => '禁用'
		);
	}

    public function roleOptions() {
            return array(
                self::ROLE_ADMIN => '管理员',
                self::ROLE_USER => '会员'
            );
    }

	public function getRoleName() {
		$role = $this->roleOptions();
		return isset($role[$this->userRole]) ? $role[$this->userRole] : '未知'.$this->userRole;
	}

	public function status() {
		$status = $this->stautsOptions();
		return isset($status[$this->userStatus]) ? $status[$this->userStatus] : '未知'.$this->userStatus;
	}
	
	public function userName() {
		return $this->userNickname != '' ? $this->userNickname : $this->userEmail;
	}
	
	public function findByEmail($email) {
		return $this->find('userEmail = ?', array($email));
	}
	
	public function getForgotPasswordUrl() {
		if(($c = Yii::app()->getController()) !== null) {
			return $c->createAbsoluteUrl('/users/resetpassword', array( 
					'encoded' => md5($this->userPassword),
					'email' => urlencode($this->userEmail)
				)
			);
		}
		return false;
	}
	
	static public function isAdmin() {
		$result = isset(Yii::app()->user->id) && Yii::app()->user->getState('userRole') == Users::ROLE_ADMIN ? Yii::app()->user->id : false;
		return $result;
	}
}
